//
//  HWTeaClockViewController.m
//  HuaWan
//
//  Created by HuaWan on 2023/10/22.
//  Copyright © 2023 HuaWan. All rights reserved.
//

#import "HWTeaClockViewController.h"

#import "HWDateCell.h"
#import "HWTeaCalendarCell.h"
#import "HWTeaClockAddButtonCell.h"

#import "HWTeaSelectAlertView.h"
#import "HWCustomSheet.h"
#import "HWCustomRemarkSheet.h"

#import "BRDatePickerView.h"

@interface HWTeaClockViewController ()

@property (nonatomic,copy) NSString *month;
@property (nonatomic,copy) NSString *selectDay;
@property (nonatomic, strong) HWTeaModel *teaModel;
@property (nonatomic, strong) HWTeaSelectAlertView *teaSelectAlertView;
@property (nonatomic, strong) HWCustomSheet *customSheet;
@property (nonatomic, strong) HWCustomRemarkSheet *customRemarkSheet;
@property (nonatomic, strong) HWTypeModel *typeModel;

@end

@implementation HWTeaClockViewController

- (void)viewDidLoad {

    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = UIColorFromHex(0xBC7C7C);
    [self setNavigationItemTitleViewWithTitle:@"奶茶记录打卡"];
    
    //用于格式化NSDate对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设置格式：zzz表示时区
    [dateFormatter setDateFormat:@"yyyy-MM"];
    _month = [dateFormatter stringFromDate:[NSDate date]];
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    _selectDay = [dateFormatter stringFromDate:[NSDate date]];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"HWDateCell" bundle:nil] forCellReuseIdentifier:@"HWDateCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"HWTeaCalendarCell" bundle:nil] forCellReuseIdentifier:@"HWTeaCalendarCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"HWTeaClockAddButtonCell" bundle:nil] forCellReuseIdentifier:@"HWTeaClockAddButtonCell"];
    
    self.tableView.frame = CGRectMake(0,self.navigationBarHeight, kScreenWidth, kScreenHeight - self.navigationBarHeight);
    
    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    //增加监听，当键退出时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}

#pragma mark - cellDataSource

- (NSArray *)cellDataSource {
    
    if (!self.dataSource) {
        NSMutableArray *arr = [NSMutableArray arrayWithCapacity:4];
        
        __block NSMutableArray *subarr = nil;
        __block NSDictionary *dict = nil;
        
        subarr = [NSMutableArray arrayWithCapacity:1];
        
        dict =  @{@"class":HWDateCell.class,
                  @"height":@([HWDateCell getCellFrame:[NSNumber numberWithFloat:96]]),
                  @"data":[HWDateCellModel ittemModelWithMonth:_month],
                  @"delegate":@YES};
        [subarr addObject:dict];

        dict =  @{@"class":HWTeaCalendarCell.class,
                  @"height":@([HWTeaCalendarCell getCellFrame:[HWTeaCalendarCellModel ittemModelWithMonth:_month selectDay:_selectDay]]),
                  @"data":[HWTeaCalendarCellModel ittemModelWithMonth:_month selectDay:_selectDay],
                  @"delegate":@YES};
        [subarr addObject:dict];
        
        dict =  @{@"class":HWTeaClockAddButtonCell.class,
                  @"height":@([HWTeaClockAddButtonCell getCellFrame:[NSNumber numberWithFloat:115]]),
                  @"delegate":@YES};
        [subarr addObject:dict];
        
        [arr addObject:subarr];
        
        self.dataSource = arr;
    }
    return self.dataSource;
}

#pragma mark HWDateCellDelegate 日期选择

- (void)dateCell:(HWDateCell *)cell button:(UIButton *)sender {
    [self showDatePickerView];
}

#pragma mark HWTeaCalendarCellDelegate

- (void)teaCalendarCell:(HWTeaCalendarCell *)cell button:(UIButton *)sender {
    HWTeaModel *teaModel = [kDataManager querTeaDataDicWithDate:cell.model.selectDay];
    self.teaModel = teaModel;
    [self showCustomRemarkSheet];
}

#pragma mark HWTeaClockAddButtonCellDelegate 添加奶茶打卡

- (void)teaClockAddButtonCell:(HWTeaClockAddButtonCell *)cell button:(UIButton *)sender {
    [self.teaSelectAlertView show];
}

#pragma mark HWCustomSheetDelegate 品牌名称输入 奶茶图标选择

- (void)customSheet:(HWCustomSheet *)sheet textField:(UITextField *)textField {
    self.typeModel.name = (NSString *)textField.text;
}

- (void)customSheet:(HWCustomSheet *)sheet buttonAction:(UIButton *)sender {
    if (sender.tag == 20) {
        if (self.typeModel.name.length > 0) {
            [kDataManager addTypeDataWithModel:self.typeModel];
            
            [self.teaSelectAlertView show];
            
            [self.typeModel defauleData];
            
            sheet.textField.text = @"";
            [sheet.textField resignFirstResponder];
            
            [UIView animateWithDuration:0.5 animations:^{
                self.customSheet.myView.alpha = 0;
                self.customSheet.maskView.alpha = 0;
            } completion:^(BOOL finished) {
                self.customSheet.hidden = YES;
            }];
        } else {
            [self showProgressHUD:@"请输入奶茶品牌"];
        }
    } else if (sender.tag >= 10 && sender.tag <= 13) {
        if (sender.tag == 10) {
            self.typeModel.isCustom = YES;
            self.typeModel.ico = @"one_tea";
        } else if (sender.tag == 11) {
            self.typeModel.isCustom = YES;
            self.typeModel.ico = @"two_tea";
        } else if (sender.tag == 12) {
            self.typeModel.isCustom = YES;
            self.typeModel.ico = @"three_tea";
        } else if (sender.tag == 13) {
            self.typeModel.isCustom = YES;
            self.typeModel.ico = @"four_tea";
        }
        
        [sheet.myButtons enumerateObjectsUsingBlock:^(UIButton *b, NSUInteger idx, BOOL * _Nonnull stop) {
            if (sender.tag == b.tag) {
                b.layer.borderWidth = 1.0;
            } else {
                b.layer.borderWidth = 0.0;
            }
            b.layer.borderColor = [UIColor grayColor].CGColor;
        }];
    } else {
    
        [sheet.textField resignFirstResponder];
        
        [UIView animateWithDuration:0.5 animations:^{
            self.customSheet.myView.alpha = 0;
            self.customSheet.maskView.alpha = 0;
        } completion:^(BOOL finished) {
            self.customSheet.hidden = YES;
        }];
    }
}

#pragma mark HWCustomSheetDelegate 备注输入 完成

- (void)customRemarkSheet:(HWCustomRemarkSheet *)cell textView:(UITextView *)textView {
    self.teaModel.remark = (NSString *)textView.text;
}

- (void)customRemarkSheet:(HWCustomRemarkSheet *)sheet buttonAction:(UIButton *)sender {
    if (sender.tag == 11) {
        //完成
        [kDataManager addTeaDataWithModel:self.teaModel];
        [self refreshData];
    } else {
        [self.teaModel defauleData];
    }
    
    [sheet.textView resignFirstResponder];
    
    [UIView animateWithDuration:0.5 animations:^{
        self.customRemarkSheet.myView.alpha = 0;
        self.customRemarkSheet.maskView.alpha = 0;
    } completion:^(BOOL finished) {
        self.customRemarkSheet.hidden = YES;
    }];
}

#pragma mark - Action

- (void)showCustomSheet {
    
    self.customSheet.hidden = NO;
        
    [self.customSheet setData:[HWCustomSheetModel ittemModelWithText:@""] delegate:self];
    
    [UIView animateWithDuration:0.5 animations:^{
        self.customSheet.myView.alpha = 1;
        self.customSheet.maskView.alpha = 0.5;
    } completion:^(BOOL finished) {
        
    }];
}

- (void)showCustomRemarkSheet {
    
    self.customRemarkSheet.hidden = NO;
        
    [self.customRemarkSheet setData:[HWCustomRemarkSheetModel ittemModelWithIco:self.teaModel.ico name:self.teaModel.name text:self.teaModel.remark tip:@"输入文字内容" max:@"50"] delegate:self];
    
    [UIView animateWithDuration:0.5 animations:^{
        self.customRemarkSheet.myView.alpha = 1;
        self.customRemarkSheet.maskView.alpha = 0.5;
    } completion:^(BOOL finished) {
        
    }];
}

//时间选择
- (void)showDatePickerView {
    @weakify(self);
    // 1.创建日期选择器
    BRDatePickerView *datePickerView = [[BRDatePickerView alloc]init];
    // 2.设置属性
    datePickerView.pickerMode = BRDatePickerModeYM;
    datePickerView.title = @"选择日期";
    datePickerView.selectDate = nil;
    datePickerView.minDate = nil;
    datePickerView.maxDate = nil;
    datePickerView.isAutoSelect = NO;
    datePickerView.resultBlock = ^(NSDate *selectDate, NSString *selectValue) {
        NSLog(@"选择的值：%@", selectValue);
        @strongify(self);
        _month = selectValue;
        [self refreshData];
    };
    // 设置自定义样式
    BRPickerStyle *customStyle = [[BRPickerStyle alloc]init];
    customStyle.alertViewColor = UIColorFromHex(0xFFFFFF);
    customStyle.pickerColor = UIColorFromHex(0xFFFFFF);
    customStyle.titleBarColor = UIColorFromHex(0xFFFFFF);
    customStyle.topCornerRadius = 20;
    customStyle.titleBarHeight = 56;
    customStyle.hiddenTitleLine = YES;
    customStyle.separatorHeight = 0;
    customStyle.separatorColor = [UIColor clearColor];
    
    /** 设置 picker 文本的颜色。暂不支持日期选择器前4种类型 */
    customStyle.pickerTextColor = UIColorFromHexA(0x333333,0.3);

    /** 设置 picker 文本的字体。暂不支持日期选择器前4种类型 */
    customStyle.pickerTextFont = [UIFont boldSystemFontOfSize:16];

    /** 设置 picker 中间选中行文本的颜色。暂不支持日期选择器前4种类型 */
    customStyle.selectRowTextColor = UIColorFromHex(0x333333);

    /** 设置 picker 中间选中行文本的字体。暂不支持日期选择器前4种类型 */
    customStyle.selectRowTextFont = [UIFont boldSystemFontOfSize:25];;
    
    ////////////////////////// 标题栏中间label（titleLabel）///////////////////////////
    /** 设置 titleLabel 文本颜色 */
    customStyle.titleTextColor = UIColorFromHex(0x333333);
    /** 设置 titleLabel 字体大小 */
    customStyle.titleTextFont = [UIFont boldSystemFontOfSize:16];
    customStyle.titleLabelFrame = CGRectMake(kScreenWidth/2 - 200/2, 13, 200, 30);

    /////////////////////////////// 取消按钮（cancelBtn）//////////////////////////////

    /** 设置 cancelBtn 的背景颜色 */
    //customStyle.cancelColor = UIColorFromHex(0xFFFFFF);

    /** 设置 cancelBtn 标题的颜色 */
    customStyle.cancelTextColor = UIColorFromHex(0x999999);

    /** 设置 cancelBtn 标题的字体 */
    customStyle.cancelTextFont = [UIFont boldSystemFontOfSize:14];

    /** 设置 cancelBtn 的 frame */
    customStyle.cancelBtnFrame = CGRectMake(15, 13, 70, 30);

    /** 设置 cancelBtn 的边框样式 */
    customStyle.cancelBorderStyle = BRBorderStyleFill;

    /** 设置 cancelBtn 的圆角大小 */
    customStyle.cancelCornerRadius = 15;

    /** 设置 cancelBtn 的边框宽度 */
    //@property (nonatomic, assign) CGFloat cancelBorderWidth;

    /** 设置 cancelBtn 的 image */
    //@property (nullable, nonatomic, strong) UIImage *cancelBtnImage;

    /** 设置 cancelBtn 的 title */
    customStyle.cancelBtnTitle = @"取消";

    /////////////////////////////// 确定按钮（doneBtn）////////////////////////////////

    /** 设置 doneBtn 的背景颜色 */
    customStyle.doneBtnImage = [UIImage imageNamed:@"done"];

    /** 设置 doneBtn 标题的颜色 */
    customStyle.doneTextColor = UIColorFromHex(0x000000);

    /** 设置 doneBtn 标题的字体 */
    customStyle.doneTextFont = [UIFont boldSystemFontOfSize:14];

    /** 设置 doneBtn 的 frame */
    customStyle.doneBtnFrame = CGRectMake(kScreenWidth - 70 - 15, 13, 70, 30);

    /** 设置 doneBtn 的边框样式 */
    customStyle.doneBorderStyle = BRBorderStyleFill;

    /** 设置 doneBtn 的圆角大小 */
    customStyle.doneCornerRadius = 15;

    /** 设置 doneBtn 的边框宽度 */
    //@property (nonatomic, assign) CGFloat doneBorderWidth;

    /** 设置 doneBtn 的 image */
    //@property (nullable, nonatomic, strong) UIImage *doneBtnImage;

    /** 设置 doneBtn 的 title */
    customStyle.doneBtnTitle = @"确认";

    datePickerView.pickerStyle = customStyle;

    // 3.显示
    [datePickerView show];
}

#pragma mark - NSNotification

//当键盘出现或改变时调用
- (void)keyboardWillShow:(NSNotification *)aNotification {
    if ([kUserManager.userManager.viewController isEqualToString:NSStringFromClass(self.class)]) {
        //获取键盘的高度
        NSDictionary *userInfo = [aNotification userInfo];
        NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
        CGRect keyboardRect = [aValue CGRectValue];
        int height = keyboardRect.size.height;   //height 就是键盘的高度
        
        if (!self.customSheet.hidden) {
            self.customSheet.viewCenterY.constant = - height/2;
        }
        
        if (!self.customRemarkSheet.hidden) {
            self.customRemarkSheet.viewCenterY.constant = - height/2;
        }
    }
}
 
//当键盘退出时调用
- (void)keyboardWillHide:(NSNotification *)aNotification {
    if ([kUserManager.userManager.viewController isEqualToString:NSStringFromClass(self.class)]) {
        if (!self.customSheet.hidden) {
            self.customSheet.viewCenterY.constant = 0;
        }
        
        if (!self.customRemarkSheet.hidden) {
            self.customRemarkSheet.viewCenterY.constant = 0;
        }
    }
}

#pragma mark - 懒加载

- (HWTeaModel *)teaModel {
    if (!_teaModel) {
        _teaModel = [HWTeaModel new];
    }
    return _teaModel;
}

- (HWTypeModel *)typeModel {
    if (!_typeModel) {
        _typeModel = [HWTypeModel new];
    }
    return _typeModel;
}

- (HWTeaSelectAlertView *)teaSelectAlertView {
    if (!_teaSelectAlertView) {
        _teaSelectAlertView  = [HWTeaSelectAlertView instanceView];
        _teaSelectAlertView.frame = CGRectMake(0,0, kScreenWidth, kScreenHeight);
        @weakify(self);
        _teaSelectAlertView.buttonAction = ^(HWTeaSelectAlertView *alertView, UIButton *sender) {
            @strongify(self);
            if (sender.tag >= 10) {
                [self.teaModel defauleData];
                self.teaModel.isCustom = NO;
                if (sender.tag > 18) {
                    self.teaModel.isCustom = YES;
                }
                
                NSArray *ary = [kDataManager getTypeArray];
                HWTypeModel *model = ary[sender.tag - 10];
                self.teaModel.name = model.name;
                self.teaModel.ico = model.ico;

                //用于格式化NSDate对象
                NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                formatter.dateFormat = @"yyyy-MM-dd";
                NSString *today = [formatter stringFromDate:[NSDate date]];
                self.teaModel.date = today;
                
                [self showCustomRemarkSheet];
            } else if (sender.tag == 9) {
                //自定义
                self.typeModel.isCustom = YES;
                self.typeModel.ico = @"one_tea";
                [self showCustomSheet];
            }
        };
        //获取当前UIWindow 并添加一个视图
        UIApplication *ap = [UIApplication sharedApplication];
        [ap.keyWindow addSubview:_teaSelectAlertView];
    }
    return _teaSelectAlertView;
}

- (HWCustomSheet *)customSheet {
    if (!_customSheet) {
        _customSheet  = [HWCustomSheet instanceView];
        _customSheet.frame = CGRectMake(0,0, kScreenWidth, kScreenHeight);
        _customSheet.myView.alpha = 0;
        _customSheet.hidden = YES;
        //获取当前UIWindow 并添加一个视图
        UIApplication *ap = [UIApplication sharedApplication];
        [ap.keyWindow addSubview:_customSheet];
    }
    return _customSheet;
}

- (HWCustomRemarkSheet *)customRemarkSheet {
    if (!_customRemarkSheet) {
        _customRemarkSheet  = [HWCustomRemarkSheet instanceView];
        _customRemarkSheet.frame = CGRectMake(0,0, kScreenWidth, kScreenHeight);
        _customRemarkSheet.myView.alpha = 0;
        _customRemarkSheet.hidden = YES;
        //获取当前UIWindow 并添加一个视图
        UIApplication *ap = [UIApplication sharedApplication];
        [ap.keyWindow addSubview:_customRemarkSheet];
    }
    return _customRemarkSheet;
}

@end
